<template>
	<view class="ticket-container">
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<uni-icons type="spinner-cycle" size="40" color="#1989fa"></uni-icons>
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 门票卡片 -->
		<view v-else-if="ticketData" class="ticket-card">
			<!-- 顶部封面图片 -->
			<view class="ticket-header">
				<image 
					:src="ticketData.coverImage || '/static/logo.png'" 
					mode="aspectFill" 
					class="cover-image"
				></image>
			</view>
			
			<!-- 票据主体 -->
			<view class="ticket-body">
				<!-- 景点名称 -->
				<view class="sight-name">{{ ticketData.sightName }}</view>
				
				<!-- 日期和时间 -->
				<view class="info-row">
					<view class="info-item">
						<text class="info-label">年份</text>
						<text class="info-value">{{ formatDate(ticketData.orderTime) }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">Time</text>
						<text class="info-value">{{ formatTime(ticketData.orderTime) }}</text>
					</view>
				</view>
				
				<!-- 地址 -->
				<view class="address-section">
					<text class="address-label">地址</text>
					<text class="address-value">{{ ticketData.address }}</text>
				</view>
				
				<!-- 虚线分割 -->
				<view class="dashed-divider">
					<view class="left-circle"></view>
					<view class="dashed-line"></view>
					<view class="right-circle"></view>
				</view>
				
				<!-- 条形码 -->
				<view class="barcode-section">
					<canvas 
						canvas-id="barcodeCanvas" 
						class="barcode-canvas"
						:style="{ width: barcodeWidth + 'px', height: barcodeHeight + 'px' }"
					></canvas>
					<text class="barcode-number">{{ ticketData.barcodeNumber }}</text>
				</view>
			</view>
			
			<!-- 底部按钮 -->
			<view class="ticket-footer">
				<button class="use-button" @click="handleUseTicket">去使用</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { orderApi } from '../../common/api/order.js'

// 响应式数据
const loading = ref(true)
const orderId = ref('')
const ticketData = ref(null)
const barcodeWidth = ref(300)
const barcodeHeight = ref(80)

// 格式化日期
const formatDate = (dateString) => {
	if (!dateString) return ''
	const date = new Date(dateString)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	return `${year}-${month}-${day}`
}

// 格式化时间
const formatTime = (dateString) => {
	if (!dateString) return ''
	const date = new Date(dateString)
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	const ampm = date.getHours() >= 12 ? 'PM' : 'AM'
	const hours12 = date.getHours() % 12 || 12
	return `${String(hours12).padStart(2, '0')}:${minutes} ${ampm}`
}

// 获取订单详情
const getOrderDetail = async () => {
	loading.value = true
	try {
		const response = await orderApi.getOrderDetail(orderId.value)
		
		if (response.code === 200 && response.data) {
			const order = response.data
			
			// 获取第一个门票信息
			if (order.orderTickets && order.orderTickets.length > 0) {
				const firstTicket = order.orderTickets[0]
				const ticket = firstTicket.ticket
				const sight = ticket?.sight
				
				ticketData.value = {
					sightName: sight?.name || '未知景点',
					address: sight?.address || '未知地址',
					orderTime: order.paymentTime || order.createdAt,
					coverImage: sight?.images?.[0] || '/static/logo.png',
					barcodeNumber: `${orderId.value}${Date.now()}`.slice(0, 16),
					quantity: firstTicket.quantity || 1,
					unitPrice: firstTicket.unitPrice || 0
				}
				
				// 绘制条形码
				setTimeout(() => {
					drawBarcode(ticketData.value.barcodeNumber)
				}, 300)
			}
		} else {
			uni.showToast({
				title: '获取订单信息失败',
				icon: 'none'
			})
		}
	} catch (err) {
		console.error('获取订单详情失败:', err)
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 绘制条形码
const drawBarcode = (code) => {
	const ctx = uni.createCanvasContext('barcodeCanvas')
	
	// 将屏幕单位转换为像素
	const dpr = uni.getSystemInfoSync().pixelRatio || 2
	const canvasWidth = barcodeWidth.value * dpr
	const canvasHeight = barcodeHeight.value * dpr
	
	// 清空画布
	ctx.clearRect(0, 0, canvasWidth, canvasHeight)
	
	// 设置背景色
	ctx.fillStyle = '#ffffff'
	ctx.fillRect(0, 0, canvasWidth, canvasHeight)
	
	// 绘制条形码（简化版：使用竖线模拟）
	const barCount = code.length * 4
	const barWidth = canvasWidth / barCount
	
	ctx.fillStyle = '#000000'
	
	for (let i = 0; i < code.length; i++) {
		const charCode = code.charCodeAt(i)
		// 根据字符编码生成不同宽度的条纹
		const pattern = (charCode % 4) + 1
		
		for (let j = 0; j < pattern; j++) {
			const x = (i * 4 + j) * barWidth
			if (j % 2 === 0) {
				ctx.fillRect(x, 0, barWidth, canvasHeight)
			}
		}
	}
	
	ctx.draw()
}

// 去使用门票
const handleUseTicket = () => {
	uni.showModal({
		title: '使用门票',
		content: '请在景区入口出示此二维码',
		confirmText: '确定',
		success: (res) => {
			if (res.confirm) {
				// 可以添加核销逻辑
				console.log('门票已使用')
				//暂时返回个人中心，并更改门票状态为已使用
				orderApi.updateOrderStatus(orderId.value, { status: 'comment' }).then(res =>{
					if(res.code === 200){
						uni.showToast({
							title: '门票已使用',
							icon: 'success'
						})
						setTimeout(() => {
							uni.navigateBack()
			
						}, 1500)
					}
				}).catch(err =>{
					console.log(err)
				})
			}
		}
	})
}

// 页面加载
onLoad((options) => {
	if (options.orderId) {
		orderId.value = options.orderId
		getOrderDetail()
	} else {
		uni.showToast({
			title: '缺少订单ID',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
})
</script>

<style lang="scss" scoped>
.ticket-container {
	min-height: 100vh;
	background: linear-gradient(180deg, #98c3fd 0%, #5a9ef9 100%);
	padding: 40rpx 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.loading-text {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #ffffff;
		}
	}
	
	.ticket-card {
		width: 100%;
		max-width: 650rpx;
		background-color: #ffffff;
		border-radius: 32rpx;
		overflow: hidden;
		box-shadow: 0 20rpx 60rpx rgba(90, 158, 249, 0.4);
		
		// 顶部封面图
		.ticket-header {
			width: 100%;
			height: 400rpx;
			position: relative;
			overflow: hidden;
			
			.cover-image {
				width: 100%;
				height: 100%;
				display: block;
			}
		}
		
		// 票据主体
		.ticket-body {
			padding: 40rpx 40rpx 0;
			
			// 景点名称
			.sight-name {
				font-size: 44rpx;
				font-weight: bold;
				color: #2c3e50;
				line-height: 60rpx;
				margin-bottom: 30rpx;
			}
			
			// 信息行
			.info-row {
				display: flex;
				justify-content: space-between;
				margin-bottom: 30rpx;
				
				.info-item {
					flex: 1;
					
					.info-label {
						display: block;
						font-size: 24rpx;
						color: #999;
						margin-bottom: 8rpx;
					}
					
					.info-value {
						display: block;
						font-size: 28rpx;
						font-weight: 500;
						color: #333;
					}
				}
			}
			
			// 地址区域
			.address-section {
				margin-bottom: 40rpx;
				
				.address-label {
					display: block;
					font-size: 24rpx;
					color: #999;
					margin-bottom: 8rpx;
				}
				
				.address-value {
					display: block;
					font-size: 28rpx;
					color: #333;
					line-height: 40rpx;
				}
			}
			
			// 虚线分割
			.dashed-divider {
				position: relative;
				height: 2rpx;
				margin: 40rpx -40rpx;
				
				.dashed-line {
					height: 2rpx;
					background-image: repeating-linear-gradient(
						to right,
						#ddd 0rpx,
						#ddd 16rpx,
						transparent 16rpx,
						transparent 32rpx
					);
				}
				
				.left-circle,
				.right-circle {
					position: absolute;
					width: 40rpx;
					height: 40rpx;
					border-radius: 50%;
					background: linear-gradient(180deg, #98c3fd 0%, #5a9ef9 100%);
					top: 50%;
					transform: translateY(-50%);
				}
				
				.left-circle {
					left: -20rpx;
				}
				
				.right-circle {
					right: -20rpx;
				}
			}
			
			// 条形码区域
			.barcode-section {
				padding: 40rpx 0 20rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				
				.barcode-canvas {
					width: 300px;
					height: 80px;
					margin-bottom: 15rpx;
				}
				
				.barcode-number {
					font-size: 26rpx;
					color: #666;
					font-family: 'Courier New', monospace;
					letter-spacing: 2rpx;
				}
			}
		}
		
		// 底部按钮
		.ticket-footer {
			padding: 30rpx 40rpx 40rpx;
			
			.use-button {
				width: 100%;
				height: 90rpx;
				background: linear-gradient(135deg, #98c3fd 0%, #5a9ef9 100%);
				color: #ffffff;
				border-radius: 45rpx;
				font-size: 32rpx;
				font-weight: 500;
				border: none;
				box-shadow: 0 8rpx 20rpx rgba(152, 195, 253, 0.5);
				
				&:active {
					opacity: 0.8;
					transform: scale(0.98);
				}
			}
		}
	}
}
</style>

